"""
@author: liujun
@file: 2022-11-4-数据结构.py
@time: 2022/11/4 10:28
"""
import re
import random
import datetime
#string类型是不可变数据类型
# >>> str1[1] = "d"
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>

#列表
#有序项目集合
#可以存放任何类型对象
#可变数据类型

#list类型是可变数据类型，内存地址不变
# >>> a[1]=800
# >>> a
# [1, 800, 3, <built-in function print>]

#列表可以进行加法和乘法运算
# >>> [1,2]+[3,4]
# [1, 2, 3, 4]
# >>> [1,2]*2
# [1, 2, 1, 2]

#pop删除并输出返回值
# ['xxx', 'a', 'b', 'c', 'd', [1, 2, 3], 'yy']
# >>> result = a.pop()
# >>> result
# 'yy'

# member = list(range(1,31))
# while len(member) > 16:
#     i = 1
#     while i < 7:
#         member.append(member.pop(0))
#         i+=1
#     print(member.pop(0))

# lst = [2,4,5,3,6,7,9]
# num=int(input("请输入一个整数："))
# for m,i in enumerate(lst):
#     for n,j in enumerate(lst):
#         num2 = int(i)+int(j)
#         if n==m:
#             break
#         elif num == num2 :
#             print(n,m)

#元组
#有序项目集合
#可以存放任何类型对象
#不可变数据类型

#字典
#key-value
# str1 = "asfgoajgboasdjaap31"
# d={}
# for i in str1:
#     d[i] = str1.count(i)
# print(d)
# >>> d4.pop('a')
# 3
# >>> d4
# {'b': 2, 'c': 6, 'd': 5}
# >>> d3.popitem()
# ('admin', {'passwd': 'admin123', 'money': 2000})
# >>> d4.popitem()
# ('d', 5)

#集合（set）
#无序
#集合元素必须是可hash的
#天生去重
#可变数据类型
#集合可以看做一个只有key的字典
#1
l1 = "asd lseo"
print(l1.title())
#2
l2 = "abcasdoiajdsxyz"
if l2.startswith("abc") and l2.endswith("xyz"):
    print("是目标字符串")
else:
    print("不是目标字符串")
#3
list1=[]
for i in range(0, 5):
    list1.append(random.randint(1, 100))
list1.sort()
print(list1, sum(list1))
#4
list2=[1,2,3,5]
list3= list2.copy()
list3.append(5)
print(list2,list3)
#5
num = int(input("请输入一个大于2的数:"))
def itnum(num):
    for i in range(2, num-1):
        if num % i == 0:
            return False
    return True
if num >= 2:
    if itnum(num) :
        print("是素数")
    else:
        print("不是素数")
else:
    print("请输入正确的数")
#6
while True:
    choice = input("请输入100以内的数:")
    if choice == 'q':
        break
    if choice.isdigit():
        score = int(choice)
        if 1 <= score < 60:
            print("不及格")
        elif 60 <= score < 80:
            print("C")
        elif 80 <= score < 90:
            print("B")
        elif 90 <= score <= 100:
            print("A")
        else:
            print("请输入正确的分数")
    else:
        print("请输入正确的分数")

#7
music = {"华语女歌手": {"邓紫棋": ["泡沫", "光年之外"], "张韶涵": ["阿娇"]},
             "华语男歌手": {"周杰伦": ["红颜如霜", "最伟大的作品"], "许嵩": ["有何不可"]}
             }
print("界面菜单:")
print("1.华语女歌手")
print("2.华语男歌手")
while True:
    choice = input("请输入您的选择:")
    if choice == '1':
        for key in music["华语女歌手"]:
            print(key)
        singer = input("请选择歌手:")
        if singer == "邓紫棋":
            print(music["华语女歌手"]["邓紫棋"])
            song = input("请选择要播放的歌曲:")
            print(song)
        elif singer == "张韶涵":
            print(music["华语女歌手"]["张韶涵"])
            song = input("请选择要播放的歌曲:")
            print(song)
        else:
            print("没有这位歌手,请重新选择")
    elif choice == '2':
        for key in music["华语男歌手"]:
            print(key)
        singer = input("请选择歌手:")
        if singer == "周杰伦":
            print(music["华语男歌手"]["周杰伦"])
            song = input("请选择要播放的歌曲:")
            print(song)
        elif singer == "许嵩":
            print(music["华语男歌手"]["许嵩"])
            song = input("请选择要播放的歌曲:")
            print(song)
        else:
            print("没有这位歌手,请重新选择")
    elif choice == 'q':
        break
    else:
        print("请输入正确的格式")

#8
def test8():
    from datetime import datetime
    time = '30/06/2022 10-30'
    time = datetime.strptime(time, "%d/%m/%Y %H-%M")
    time1 = time.strftime('%Y-%m-%d %H:%M')
    print(time1)

#9
year = int(input("请输入年："))
month = int(input("请输入月："))
day = int(input("请输入日："))
result = datetime.datetime(year, month, day)
print(result.strftime("%j"))

#10
alf = []
num = []
other = []
strs = input("请输入一段字符：")
for i in strs:
    if i.isdigit():
        num.append(i)
    elif 'a' <= i <= 'z' or 'A' <= i <= 'Z':
        alf.append(i)
    else:
        other.append(i)
print("字母的个数是：", len(alf))
print("数字的个数是：", len(num))
print("其他字符的个数是：", len(other))



def login(name,password):
    with open("message.txt", "r", encoding='utf-8') as f:
        usr=[]
        for line in f.readlines():
            line = line.strip('\n')
            b=line.split(' ')
            usr.append(b)
    usr=dict(usr)
    if name in usr:
        r = usr[name].split(',')
        if password in r:
            print("登录成功！")
            print("下面是商品信息，输入exit可退出")
            shoppingmessage()
            print(shoppingmessage())
        else:
            print("密码错误")
    else:
        print("用户名错误")

def regist1(name,password1,password2):
    with open("message.txt", "r", encoding='utf-8') as f:
        usr = []
        for line in f.readlines():
            line = line.strip('\n')
            b = line.split(' ')
            usr.append(b)
    usr = dict(usr)
    if name in usr:
        print("用户名已存在")
    else:
        print("用户名可用")
    if password1 == password2:
        print("恭喜用户创建成功，或得100！")
        with open("message.txt", "a", encoding='utf-8') as f:
            f.write('\n' + name + ' ' + name + ',' + password1 + ',' + '100')
    else:
        print("两次密码不一致")

def shoppingmessage():
    with open("shopping.txt", "r", encoding='utf-8') as f:
        shopping = []
        for line in f.readlines():
            line = line.strip('\n')
            b = line.split(':')
            x = b[1].split(' ')
            a = {'name': '', 'price': ''}
            a['name'] = x[0]
            a['price'] = x[1]
            b[1] = a
            shopping.append(b)
    shopping = dict(shopping)
    return shopping
def exit():
    with open("shoppingcar.txt", "w", encoding='utf-8') as f:
        f.write("")

def shoppingcar(name):
    shopping = []
    with open("shoppingcar.txt", "r", encoding='utf-8') as f:
        for d in f.readlines():
            shopping.append(d.strip('\n'))
    print("商品编号   商品名称 商品数量  商品总价")
    a = 0
    for i in range(len(shopping)):
        print(shopping[i])
        price=shopping[i].split('     ')[3]
        a=float(price)+float(a)
    with open("message.txt", "r", encoding='utf-8') as f:
        usr=[]
        for line in f.readlines():
            line = line.strip('\n')
            b=line.split(' ')
            usr.append(b)
    usr=dict(usr)
    r = usr[name].split(',')
    money = r[2]
    print("你的余额为：",money)
    print("总价为：",a)
    balance = float(money) - float(a)
    return balance

def pay(name,balance):
    with open("message.txt", "r", encoding='utf-8') as f:
        usr=[]
        for line in f.readlines():
            line = line.strip('\n')
            b=line.split(' ')
            usr.append(b)
    usr1=dict(usr)
    r = usr1[name].split(',')
    z = r[0],r[1],str(balance)
    z = ','.join(z)
    with open("message.txt", "w", encoding='utf-8') as f:
        f.write("")
    for i in range(len(usr)):
        i=usr[i]
        x=i[0]
        if x=="root":
            y = z
            with open("message.txt", "a", encoding='utf-8') as f:
                f.write( x + ' ' + y)
        elif x!="root" and x==name:
            y=z
            with open("message.txt", "a", encoding='utf-8') as f:
                f.write('\n' + x + ' ' + y)
        else:
            y=i[1]
            with open("message.txt", "a", encoding='utf-8') as f:
                f.write('\n' + x + ' ' + y)
    with open("shoppingcar.txt", "w", encoding='utf-8') as f:
        f.write("")


print("欢迎来到三乐购物系统")
num = input("请选择1.登录 2.注册：")
if num == "1":
    name = input("请输入用户名：")
    password = input("请输入密码：")
    login(name,password)
    retart = True
    while retart:
        retart=False
        num = input("请选择:1.添加商品 2.查看购物车 3.结账：")
        if num == "1":
            num1 = input("请输入商品编号：")
            num2 = input("请输入购买数量：")
            shoppingmessage()
            shopping = shoppingmessage()
            shopping = shopping[num1]
            name1 = shopping['name']
            price = shopping['price']
            price = float(num2)*float(price)
            with open("shoppingcar.txt", "a", encoding='utf-8') as f:
                f.write(num1 + "     " +name1 + "     " + num2+ "     " + str(price) + '\n')
            num =input("请选择1.继续查看商品2.查看购物车 3.结账：")
            if num == "1":
                print("下面是商品信息，输入exit可退出")
                shoppingmessage()
                print(shoppingmessage())
                retart = True
            if num == "2":
                shoppingcar(name)
                print("下面是商品信息，输入exit可退出")
                shoppingmessage()
                print(shoppingmessage())
                retart = True
            if num == "3":
                pay(name,shoppingcar(name))
            if num == "exit":
                print("欢迎下次使用")
        if num == "2":
            shoppingcar(name)
            print("下面是商品信息，输入exit可退出")
            shoppingmessage()
            print(shoppingmessage())
            retart = True
        if num == "3":
            pay(name, shoppingcar(name))
        if num == "exit":
            print("欢迎下次使用")
elif num == "2":
    print("现在注册立送100")
    name = input("请输入你要注册的用户名：")
    password1 = input("请输入密码：")
    password2 = input("请再次输入密码：")
    regist1(name,password1,password2)
